<template>
  <div class="task-library">
    <h1 class="page-title">任务库管理</h1>

    <!-- 筛选区域 -->
    <el-card class="content-card filter-card" shadow="hover">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="训练领域">
          <el-select
            v-model="filterForm.domain"
            placeholder="全部领域"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in domainOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="难度等级">
          <el-select
            v-model="filterForm.difficulty"
            placeholder="全部难度"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in difficultyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="适用年龄">
          <el-input-number
            v-model="filterForm.age"
            :min="0"
            :max="18"
            placeholder="年龄"
            controls-position="right"
            style="width: 120px"
            @change="handleAgeChange"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchTasks">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加自定义任务
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 任务列表 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>任务列表 (共 {{ totalTasks }} 个)</span>
        </div>
      </template>

      <div v-loading="loading" class="task-list">
        <el-empty v-if="taskList.length === 0" description="暂无任务数据" />

        <div
          v-for="task in taskList"
          :key="task.id"
          class="task-card"
        >
          <div class="task-header">
            <div class="task-title-area">
              <h3>{{ task.title }}</h3>
              <el-tag v-if="!task.isPublic" type="warning">
                自定义
              </el-tag>
            </div>
            <div class="task-tags">
              <el-tag type="info">
                {{ getDomainText(task.domain) }}
              </el-tag>
              <el-tag type="warning">
                {{ getDifficultyText(task.difficulty) }}
              </el-tag>
            </div>
          </div>

          <div class="task-body">
            <p class="task-description">{{ task.description }}</p>
            <div class="task-details">
              <span v-if="task.durationMinutes">
                <el-icon><Clock /></el-icon>
                建议时长：{{ task.durationMinutes }}分钟
              </span>
              <span v-if="task.recommendedFrequency">
                <el-icon><Calendar /></el-icon>
                建议频率：{{ getFrequencyText(task.recommendedFrequency) }}
              </span>
            </div>
          </div>



          <div class="task-actions">
            <el-tag v-if="task.inGrowthBox" type="success" size="large">
              <el-icon><Check /></el-icon>
              已在成长盒
            </el-tag>
            <div v-else>
              <!-- 只有自定义任务才显示编辑按钮 -->
              <el-button
                v-if="!task.isPublic"
                size="large"
                style="margin-right: 10px"
                @click="showModifyDialog(task)"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="markAsMastered(task)"
              >
                收纳进成长盒
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页组件 -->
      <div v-if="totalTasks > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalTasks"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

<!--  添加编辑任务对话框  -->
    <el-dialog
      v-model = "modifyDialogVisible"
      title="编辑内容"
      width="600px"
    >
      <el-form
        ref="modifyFormRef"
        :model="modifyForm"
        :rules = "addRules"
      >
        <el-form-item label="任务标题" >
          <el-input
          v-model="modifyForm.title"
          placeholder="输入修改内容"
          />
        </el-form-item>

        <el-form-item label="任务描述" prop="description">
          <el-input
              v-model="modifyForm.description"
              type="textarea"
              :rows="3"
              placeholder="描述训练方法和目标"
          />
        </el-form-item>

        <el-form-item label="训练领域" prop="domain">
          <el-select
              v-model="modifyForm.domain"
              placeholder="请选择"
              style="width: 100%"
          >
            <el-option
                v-for="item in domainOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="难度等级" prop="difficulty">
          <el-select
              v-model="modifyForm.difficulty"
              placeholder="请选择"
              style="width: 100%"
          >
            <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="适用年龄">
          <el-col :span="11">
            <el-input-number
                v-model="modifyForm.ageMin"
                :min="0"
                :max="18"
                placeholder="最小"
                controls-position="right"
                style="width: 100%"
            />
          </el-col>
          <el-col :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-input-number
                v-model="modifyForm.ageMax"
                :min="0"
                :max="18"
                placeholder="最大"
                controls-position="right"
                style="width: 100%"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="建议训练时长">
          <el-input-number
              v-model="modifyForm.durationMinutes"
              :min="1"
              :max="120"
              placeholder="分钟"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="建议频率">
          <el-select
              v-model="modifyForm.recommendedFrequency"
              placeholder="请选择"
              style="width: 100%"
          >
            <el-option
                v-for="item in frequencyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>



      </el-form>


      <template #footer>
        <el-button @click="modifyDialogVisible = false">取消</el-button>
        <el-button color="red" @click="handleDeleteTask">
          <el-icon><delete/></el-icon> 删除任务
        </el-button>
        <el-button type="primary" :loading="submitting" @click="handleModifyTask">保存修改</el-button>
      </template>
    </el-dialog>
<!-- 其实原本不用这么麻烦的,可以直接修改原表单通过判定得到效果的,那样可能更不容易出问题,但是写都写了,看看   -->


    <!-- 添加自定义任务对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加自定义任务"
      width="600px"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="110px"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input
            v-model="addForm.title"
            placeholder="例如：自己整理书包"
          />
        </el-form-item>

        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="addForm.description"
            type="textarea"
            :rows="3"
            placeholder="描述训练方法和目标"
          />
        </el-form-item>

        <el-form-item label="训练领域" prop="domain">
          <el-select
            v-model="addForm.domain"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in domainOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="难度等级" prop="difficulty">
          <el-select
            v-model="addForm.difficulty"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in difficultyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="适用年龄">
          <el-col :span="11">
            <el-input-number
              v-model="addForm.ageMin"
              :min="0"
              :max="18"
              placeholder="最小"
              controls-position="right"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="2" style="text-align: center">-</el-col>
          <el-col :span="11">
            <el-input-number
              v-model="addForm.ageMax"
              :min="0"
              :max="18"
              placeholder="最大"
              controls-position="right"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>

        <el-form-item label="建议训练时长">
          <el-input-number
            v-model="addForm.durationMinutes"
            :min="1"
            :max="120"
            placeholder="分钟"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="建议频率">
          <el-select
            v-model="addForm.recommendedFrequency"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in frequencyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleAddTask">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { getTaskListPage, addCustomTask, modifyCustomTask, deleteCustomTask } from '@/api/task'
import { addTaskToGrowthBox, getGrowthBoxTaskIds } from '@/api/growthBox'
import {
  DOMAIN_MAP,
  DIFFICULTY_MAP,
  FREQUENCY_MAP,
  DOMAIN_OPTIONS,
  DIFFICULTY_OPTIONS,
  FREQUENCY_OPTIONS,
  DIFFICULTY_AGE_MAP
} from '@/utils/constants'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Delete} from "@element-plus/icons-vue";

const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const taskList = ref([])
const totalTasks = ref(0)
const addDialogVisible = ref(false)
const modifyDialogVisible = ref(false)
const addFormRef = ref()
const modifyFormRef = ref()

const domainOptions = DOMAIN_OPTIONS
const difficultyOptions = DIFFICULTY_OPTIONS
const frequencyOptions = FREQUENCY_OPTIONS

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 20
})

// 筛选表单
const filterForm = reactive({
  domain: '',
  difficulty: null,
  age: null
})

// 添加任务表单
const addForm = reactive({
  title: '',
  description: '',
  domain: '',
  difficulty: null,
  ageMin: 3,
  ageMax: 6,
  durationMinutes: 15,
  recommendedFrequency: 'daily'
})

const modifyForm = reactive({
  id: null,
  title: '',
  description: '',
  domain: '',
  difficulty: 1,  // 默认基础难度
  ageMin: 0,
  ageMax: 6,
  durationMinutes: 15,
  recommendedFrequency: 'daily'
})

const addRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  domain: [
    { required: true, message: '请选择训练领域', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ]
}

const getDomainText = (domain) => {
  return DOMAIN_MAP[domain] || domain
}

const getDifficultyText = (difficulty) => {
  return DIFFICULTY_MAP[difficulty] || difficulty
}

const getFrequencyText = (frequency) => {
  return FREQUENCY_MAP[frequency] || frequency
}
// 监听难度等级变化，自动更新适用年龄
watch(() => addForm.difficulty, (newDifficulty) => {
  if (newDifficulty && DIFFICULTY_AGE_MAP[newDifficulty]) {
    const ageRange = DIFFICULTY_AGE_MAP[newDifficulty]
    addForm.ageMin = ageRange.min
    addForm.ageMax = ageRange.max
  }
})

// 加载任务列表 - 使用分页查询
const loadTasks = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    if (filterForm.domain) params.domain = filterForm.domain
    if (filterForm.difficulty !== null) params.difficulty = filterForm.difficulty
    if (filterForm.age !== null) params.age = filterForm.age

    // 并行加载任务列表和成长盒任务ID
    const [pageResult, growthBoxResponse] = await Promise.all([
      getTaskListPage(params),
      getGrowthBoxTaskIds()
    ])
    
    // 处理分页结果
    taskList.value = pageResult.records || []
    totalTasks.value = pageResult.total || 0
    
    // 批量标记任务是否在成长盒中
    if (growthBoxResponse.code === 200) {
      const growthBoxTaskIds = new Set(growthBoxResponse.data || [])
      taskList.value.forEach(task => {
        task.inGrowthBox = growthBoxTaskIds.has(task.id)
      })
    }
  } catch (error) {
    console.error('加载任务失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索任务
const searchTasks = () => {
  pagination.pageNum = 1 // 重置到第一页
  loadTasks()
}

// 重置筛选
const resetFilter = () => {
  filterForm.domain = ''
  filterForm.difficulty = null
  filterForm.age = null
  pagination.pageNum = 1 // 重置到第一页
  loadTasks()
}

// 分页大小变化
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.pageNum = 1 // 重置到第一页
  loadTasks()
}

// 页码变化
const handlePageChange = (newPage) => {
  pagination.pageNum = newPage
  loadTasks()
}

// 防抖定时器
let debounceTimer = null

// 防抖搜索函数
const debounceSearch = () => {
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  debounceTimer = setTimeout(() => {
    pagination.pageNum = 1
    loadTasks()
  }, 500) // 500ms 延迟
}

// 年龄输入变化时防抖搜索
const handleAgeChange = () => {
  debounceSearch()
}

//显示编辑对话框
const showModifyDialog = (task) => {
  // 将任务数据填充到编辑表单
  Object.assign(modifyForm, {
    id: task.id,
    title: task.title,
    description: task.description,
    domain: task.domain,
    difficulty: task.difficulty,
    ageMin: task.ageMin,
    ageMax: task.ageMax,
    durationMinutes: task.durationMinutes,
    recommendedFrequency: task.recommendedFrequency
  })
  modifyDialogVisible.value = true
}

// 显示添加对话框
const showAddDialog = () => {
  addDialogVisible.value = true
}

// 添加自定义任务
const handleAddTask = async () => {
  await addFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await addCustomTask(addForm)
        ElMessage.success('添加成功')
        addDialogVisible.value = false
        resetAddForm()
        loadTasks()
      } finally {
        submitting.value = false
      }
    }
  })
}
//修改自定义任务
const handleModifyTask = async () => {
  await modifyFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        await modifyCustomTask(modifyForm)
        ElMessage.success('修改成功')
        modifyDialogVisible.value = false
        resetModifyForm()
        loadTasks()
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除自定义任务
const handleDeleteTask = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个自定义任务吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    submitting.value = true
    try {
      const response = await deleteCustomTask(modifyForm.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        modifyDialogVisible.value = false
        resetModifyForm()
        loadTasks()
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } finally {
      submitting.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 重置添加表单
const resetAddForm = () => {
  Object.assign(addForm, {
    title: '',
    description: '',
    domain: '',
    difficulty: 1,  // 默认基础难度
    ageMin: 0,
    ageMax: 6,
    durationMinutes: 15,
    recommendedFrequency: 'daily'
  })
}
//从这可以看出表单中的数值就是一堆键值对的组合

const resetModifyForm = () => {
  Object.assign(modifyForm, {
    id: null,
    title: '',
    description: '',
    domain: '',
    difficulty: null,
    ageMin: 3,
    ageMax: 6,
    durationMinutes: 15,
    recommendedFrequency: 'daily'
  })
}

// 标记为已掌握
const markAsMastered = async (task) => {
  try {
    const { value: note } = await ElMessageBox.prompt(
      `确定将"${task.title}"收纳进成长盒吗？这是孩子成长的印记。`,
      '收纳确认',
      {
        confirmButtonText: '确定收纳',
        cancelButtonText: '取消',
        inputPlaceholder: '请输入备注（选填）',
        inputType: 'textarea'
      }
    )

    const response = await addTaskToGrowthBox({ taskId: task.id, note: note || '' })
    if (response.code === 200) {
      ElMessage.success('已收纳进成长盒，任务是孩子成长的印记')
      loadTasks()
    } else {
      ElMessage.error(response.message || '收纳失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('收纳失败:', error)
      // 错误消息已经在拦截器中显示，这里不需要重复显示
    }
  }
}

onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
}

.filter-form .el-form-item {
  margin-bottom: 10px;
}

.card-header {
  font-weight: bold;
}

.task-list {
  min-height: 300px;
}

.task-card {
  padding: 20px;
  margin-bottom: 15px;
  background: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #ffb3d9;
  transition: all 0.3s;
}

.task-card:hover {
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.task-title-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

.task-title-area h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.task-tags {
  display: flex;
  gap: 10px;
}

.task-body {
  margin-bottom: 15px;
}

.task-description {
  font-size: 14px;
  color: #606266;
  margin: 0 0 10px 0;
  line-height: 1.6;
}

.task-details {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 13px;
  color: #909399;
}

.task-details span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.task-actions {
  display: flex;
  justify-content: flex-end;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

@media (max-width: 768px) {
  .task-header {
    flex-direction: column;
    gap: 10px;
  }

  .task-details {
    flex-direction: column;
    gap: 8px;
  }

  .pagination-container {
    margin-top: 15px;
  }
}
</style>
